package zz.demo.springCloud.wechat.handler;


import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import zz.demo.springCloud.wechat.builder.TextBuilder;
import zz.demo.springCloud.wechat.config.WxCpServiceAdapter;
import zz.demo.springCloud.wechat.service.WeChatFeignService;
import zz.demo.springCloud.wechat.utils.JsonUtils;
import zz.demo.springCloud.wechat.vo.WeChatTextVO;

import java.util.Map;

/**
 * * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class MsgHandler extends AbstractHandler {
    @Autowired
    private WeChatFeignService weChatFeignService;

    @Override
    public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage,
                                    Map<String, Object> context, WxCpService weixinService,
                                    WxSessionManager sessionManager) {
        String content = "收到信息内容：" + JsonUtils.toJson(wxMessage) + " 11" +weixinService.getWxCpConfigStorage()
                .getAgentId();

        WxCpServiceAdapter wxCpService = (WxCpServiceAdapter) weixinService;
        if(wxCpService.isNotEmpty()){
            content = weChatFeignService.sendWeChatText(wxCpService.getWeChatApp(),convert(wxMessage));
        }

        return new TextBuilder().build(content, wxMessage, weixinService);
    }

    public WeChatTextVO convert(WeChatTextVO weChatTextVO,WxCpXmlMessage message){
        if(weChatTextVO==null){
            return null;
        }
        weChatTextVO.setAgentId(message.getAgentId());
        weChatTextVO.setMsgId(message.getMsgId());
        weChatTextVO.setContent(message.getContent());
        weChatTextVO.setCreateTime(message.getCreateTime());
        weChatTextVO.setFromUserName(message.getFromUserName());
        return weChatTextVO;
    }

    public WeChatTextVO convert(WxCpXmlMessage message){
        if(message == null){
            return null;
        }
        return convert(new WeChatTextVO(),message);
    }

}
